package cn.xf.controller;

import cn.xf.domain.Results;
import cn.xf.domain.Role;
import cn.xf.domain.UserInfo;
import cn.xf.service.IRoleService;
import cn.xf.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author xiaofu
 * @date 2021-05-18 9:41
 * @email dearaf@163.com
 */
@Controller
@RequestMapping("/user")
public class UserController {

    /*@RequestMapping("/loadUser.do")
    @ResponseBody
    public String loadUser(){
        String userName = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            userName = authentication.getName();
        }
        return userName;
        //最新用springsecurity标签可以获取当前登录的用户名
        <%@taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
        <security:authentication property="principal.username"/>
    }*/

    @Autowired
    private IUserService userService;

    /**
     * 查询所有用户
     *
     * @return
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") Integer page, @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        List<UserInfo> users = userService.findAllByPage(page, pageSize);
        PageInfo<UserInfo> pageInfo = new PageInfo<UserInfo>(users);
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("/user/user-list");
        return mv;
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/save.do")
    public String save(UserInfo user) {
        userService.save(user);
        return "redirect:findAll.do";
    }

    /**
     * 查看详情，根据ID查找单个
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id", required = true) String id) {
        UserInfo user = userService.findById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", user);
        mv.setViewName("/user/user-show");
        return mv;
    }

    @Autowired
    private IRoleService roleService;

    /**
     * 根据ID查找此用户下所有的角色，返回添加角色界面
     *
     * @param id
     * @return
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id) {
        UserInfo user = userService.findById(id);
        //查找此用户可以添加的角色的名称
        List<Role> roleList = roleService.findOtherRole(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", user);
        mv.addObject("roleList", roleList);
        mv.setViewName("/user/user-role-add");
        return mv;
    }

    /**
     * 将角色添加到用户
     *
     * @param userId
     * @param ids
     * @return
     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(String userId, String[] ids) {
        userService.addRoleToUser(userId, ids);
        return "redirect:findAll.do";
    }

    //定义结果集
    private Results results = new Results();

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @RequestMapping("/changePWD.do")
    public ModelAndView changePWD(@RequestParam("oldPass") String oldPass, @RequestParam("newPass1") String newPass1, @RequestParam("newPass2") String newPass2) {

        //System.out.println(oldPass);
        //获取登陆用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        UserInfo loginUser = userService.findByUsername(username);

        boolean matches = passwordEncoder.matches(oldPass, loginUser.getPassword());
        ModelAndView mv = new ModelAndView();
        //判断旧密码和数据库密码是否匹配，如果不匹配不允许修改,返回错误信息
        if (!matches) {
            results.setMess("原密码错误，请重新输入！");
            mv.addObject("results", results);
            mv.setViewName("error");
            return mv;
        }
        //匹配，判断两次密码不能为空，并且输入是否一致，如果不一致不允许修改
        if ("".equals(newPass1) || "".equals(newPass2)) {
            results.setMess("新密码不可为空！");
            mv.addObject("results", results);
            mv.setViewName("error");
            return mv;
        }
        if (!newPass1.equals(newPass2)) {
            results.setMess("两次密码输入不一致！");
            mv.addObject("results", results);
            mv.setViewName("error");
            return mv;
        }
        //暂时不判断弱密码，密码一致等可从前台正则表达式判断
        //校验通过，保存密码
        loginUser.setPassword(passwordEncoder.encode(newPass2));
        userService.update(loginUser);
        mv.setViewName("../login");
        return mv;
    }

}
